package com.example.qxfw.shfx.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dmgis.entity.DmMapPoint;
import com.example.qxfw.common.entity.qx.WaterStation;
import com.example.qxfw.common.entity.zy.Flooded;
import com.example.qxfw.common.util.DateUtil;
import com.example.qxfw.qxxx.mapper.WaterStationMapper;
import com.example.qxfw.shfx.Mapper.FloodedMapper;
import com.example.qxfw.shfx.Service.FxyaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class FxyaServiceImpl implements FxyaService {
    @Autowired
    private WaterStationMapper waterStationMapper;
    @Autowired
    private FloodedMapper floodedMapper;

    @Override
    public HashMap<String, DmMapPoint> getAllOfWaterStation() {
        List<WaterStation> waterStations = waterStationMapper.selectList(new LambdaQueryWrapper<WaterStation>()
                .select(WaterStation::getStnm, WaterStation::getLgtd, WaterStation::getLttd));
        HashMap<String, DmMapPoint> map = new HashMap<>();
        for (WaterStation waterStation : waterStations) {
            String name = waterStation.getStnm().trim();
            DmMapPoint dmMapPoint = new DmMapPoint();
            dmMapPoint.setX(Double.parseDouble(waterStation.getLgtd()));
            dmMapPoint.setY(Double.parseDouble(waterStation.getLttd()));
            map.put(name, dmMapPoint);
        }
        return map;
    }

    @Override
    public List<Flooded> getAllOfFlooded() {
        return floodedMapper.selectList(null);
    }

    @Override
    public int deleteOfFlooded(int id) {
        return floodedMapper.deleteById(id);
    }

    @Override
    public Flooded insertOfFlooded(Flooded flooded) {
        Timestamp timestamp = DateUtil.localDateTimeToTimestamp(LocalDateTime.now());
        flooded.setTime(timestamp);
        WaterStation waterStation = waterStationMapper.selectOne(new LambdaQueryWrapper<WaterStation>()
                .eq(WaterStation::getStnm, flooded.getStationname()));
        String stlc = waterStation.getStlc();
        String target = "市";
        int startIndex = stlc.indexOf(target);
        String extractedString = stlc.substring(0, startIndex + target.length());
        flooded.setCity(extractedString.substring(2, startIndex));
        int insert = floodedMapper.insert(flooded);
        if (insert > 0) {
            return flooded;
        }else {
            return null;
        }
    }
}
